package com.example.springboot.config.schedule;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class CacheManager {
    private static String accessToken;
    private static long expiresTime;
    private static String appid;
    private static String appSecret;

    @Value("${wx.mp.appid}")
    public void setAppid(String appid) {
        CacheManager.appid = appid;
    }

    @Value("${wx.mp.appSecret}")
    public void setAppSecret(String appSecret) {
        CacheManager.appSecret = appSecret;
    }

    public static synchronized String getAccessToken() {
        if (accessToken == null || System.currentTimeMillis() > expiresTime) {
            accessToken = refreshAccessToken();
        }
        return accessToken;
    }

    public static String refreshAccessToken() {
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appid, appSecret);
        try {
            String response = HttpUtil.get(url);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            if (jsonObject.containsKey("access_token")) {
                accessToken = jsonObject.getStr("access_token");
                expiresTime = System.currentTimeMillis() + (jsonObject.getInt("expires_in") - 200) * 1000;
                return accessToken;
            } else {
                System.out.println("Error getting access token: " + jsonObject.getStr("errmsg"));
                return null;
            }
        } catch (Exception e) {
            System.out.println("Error retrieving access token: " + e.getMessage());
            return null;
        }
    }
}
